<?php

class Model_Auth {
    
    public function login($username, $password) {
        $where = array(
            'username' => $username,
            'status' => 'normal'
        );
        $m_member = Model::factory('admin');
        $user = $m_member->getRow($where);

        $password = $this->hash($password);
        if (!empty($user) && $user['password'] == $password) {
            return $user;
        }
        return FALSE;
    }

    public function complete_login($user) {
        $client_ip = Func::get_client_ip();
        
        $m_member = Model::factory('admin');
        $m_member->updateById(array('last_login'=>time(), 'client_ip'=>$client_ip), $user['id']);
        $user = array_intersect_key($user, array('id'=>1, 'username'=>1, 'role_id'=>1));

        Cookie::set('user_info', json_encode($user), 0);
    }
    
    public function get_user() {
        $user_info = Cookie::get('user_info');
        if (!empty($user_info)) {
            return json_decode($user_info, true);
        } else {
            return array();
        }
    }
    
    public function logout() {
        Cookie::delete('user_info');
        return true;
    }
    
    public function hash($str) {
        return hash_hmac('sha256', $str, '%@#$!^*&');
    }

    public function force_login($user) {
        return $this->complete_login($user);
    }
    
    public function check_password($password) {
        $user = $this->get_user();
        $where = array(
            'username' => $user['username'],
            'status' => 'normal'
        );
        $m_member = Model::factory('admin');
        $user = $m_member->getRow($where);
        if (empty($user)) {
            return FALSE;
        }
    
        $hash = $this->hash($password);
        return $hash == $user['password'];
    }
    
    public function change_password($password) {
        $user = $this->get_user();
        if (empty($user)) {
            return FALSE;
        }
    
        $password = $this->hash($password);
        $data = array(
            'password' => $password
        );
        $m_member = Model::factory('admin');
        $ret = $m_member->updateById($data, $user['id']);
        return $ret;
    }
} 
